package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service

public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper ;

    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    public void insert(Permission permission) {
        permissionMapper.insert(permission);
    }

    public Permission selectOne(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize() );
        List<Permission> list = permissionMapper.queryForList(qo);
        return new PageInfo<Permission>(list);
    }

    @Autowired
    private ApplicationContext ctx ;
    @Override
    public void reload() {
        //把每个控制器中贴了权限注解的方法转化为权限数据,并插入数据
        List<String> expressions = permissionMapper.selectAllExpression();
        //1.获取所有的控制器
        Map<String,Object> map = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = map.values();
        //2.遍历每个控制器中的方法
        for (Object controller : controllers) {
            Class<?> clazz = controller.getClass();
            Method[] methods = clazz.getDeclaredMethods();
            //3.遍历到每个方法
            for (Method method : methods) {
                //4.判断是否有贴自定义的注解
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                if(annotation!=null){
                    String name = annotation.name();
                    String expression = annotation.expression();
                    if(!expressions.contains(expression)){
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        System.out.println(permission);
                        permissionMapper.insert(permission);
                    }
                }
            }
        }
    }
    @Override
    public List<String> selectByEmpId(Long id) {
        return permissionMapper.selectByEmpId(id);
    }
}
